package com.itcast.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcast.reggie.Dto.OrderDto;
import com.itcast.reggie.commen.CustomException;
import com.itcast.reggie.mapper.OrdersDao;
import com.itcast.reggie.pojo.*;
import com.itcast.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService{
    @Autowired
    private HttpSession session;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;

    //保存订单
    @Override
    public void submit(Orders order) {
        //IdWorker 获取随机id的工具
        long orderId = IdWorker.getId();//订单号
        //获取当前用户id,查询购物车数据
        Long userId = (Long) session.getAttribute("UserId");
        QueryWrapper<ShoppingCart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<ShoppingCart> list = shoppingCartService.list(wrapper);
        if(list == null || list.size() == 0){
            throw new CustomException("购物车为空，不能下单");
        }
       //根据id查询用户数据
        User user = userService.getById(userId);
        //根据地址id查地址数据
        AddressBook adderss = addressBookService.getById(order.getAddressBookId());
        if(adderss == null){
            throw new CustomException("用户地址信息有误，不能下单");
        }
        AtomicInteger amount = new AtomicInteger(0);//求总价的工具,有原子性
        //组装订单明细数据,批量保存订单明细
        List<OrderDetail> orderDetailCollect = list.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(item,orderDetail);
            orderDetail.setOrderId(orderId);
            /*orderDetail.setName(item.getName());
            orderDetail.setDishId(item.getId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setNumber(item.getNumber());
            orderDetail.setAmount(item.getAmount());
            orderDetail.setImage(item.getImage());*/
            //一个具有原子性的求和工具
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        orderDetailService.saveBatch(orderDetailCollect);
        //组装订单数据.保存
        Orders LocalOrder = new Orders();
        LocalOrder.setNumber(orderId+"");
        LocalOrder.setStatus(2);
        LocalOrder.setUserId(user.getId());
        LocalOrder.setAddressBookId(adderss.getId());
        LocalOrder.setOrderTime(LocalDateTime.now());
        LocalOrder.setCheckoutTime(LocalDateTime.now());
        LocalOrder.setPayMethod(order.getPayMethod());
        LocalOrder.setAmount(BigDecimal.valueOf(amount.get())); //总金额
        LocalOrder.setRemark(order.getRemark());
        LocalOrder.setUserName(user.getName());
        LocalOrder.setPhone(user.getPhone());
        LocalOrder.setAddress(adderss.getDetail());
        LocalOrder.setConsignee(adderss.getConsignee());
        save(LocalOrder);
        //清空购物车
        shoppingCartService.remove(wrapper);
    }

    //查找订单
    @Override
    public Page<Orders> getPages(int page, int pageSize, String number, LocalDateTime beginTime, LocalDateTime endTime) {
        Page<Orders> orders = new Page<>(page,pageSize);
        QueryWrapper<Orders> wrapper2= new QueryWrapper<>();
        wrapper2.eq(StringUtils.hasText(number),"number",number);
        if (beginTime != null && endTime != null) {
            wrapper2.between("order_time" ,beginTime,endTime);
        }
        page(orders,wrapper2);
        //查找订单数据,orderDto
        List<Orders> records = orders.getRecords();
        List<Orders> localOrder = records.stream().map((order) -> {
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(order, orderDto);
            //获取订单号
            String DishNumber = order.getNumber();
            //从order_detail表中查订单详细数据
            QueryWrapper<OrderDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("order_id", DishNumber);
            List<OrderDetail> list = orderDetailService.list(wrapper);
            //保存到orderDto里面
            orderDto.setOrderDetailList(list);
            //封装一下这一单一共几个商品
            int DishNum = 0;
            for (OrderDetail orderDetail : list) {
                DishNum +=orderDetail.getNumber();
            }
            orderDto.setSumNum(DishNum);
            return orderDto;
        }).collect(Collectors.toList());
        orders.setRecords(localOrder);
        return orders;
    }
}
